<template>
  <div>
    <el-container>
      <el-header
        style="
          background-color: #687581;
          height: 60px;
          color: #fff;
          font-size: 30px;
        "
        >车辆信息
      </el-header>
    </el-container>

    <el-container>
      <el-aside width="200px">
        <el-menu
          default-active="1-1"
          class="el-menu-vertical-demo"
          @open="handleOpen"
          @close="handleClose"
          background-color="#545c64"
          text-color="#fff"
          active-text-color="#ffd04b"
        >
          <el-submenu index="1">
            <template slot="title">
              <i class="el-icon-more"></i>
              <span slot="title">
                <span>车辆信息</span>
              </span>
            </template>
            <el-menu-item-group>
              <el-menu-item
                index="1-1"
                @click="
                  get1stPageSharedEbike()
                  EbikePage = true
                  bikePage = false
                  personalEbikePage = false
                  plcholder = plcholderForm.ebike
                "
                >共享电动车</el-menu-item
              >
              <el-menu-item
                index="1-2"
                @click="
                  get1stPageSharedBike()
                  EbikePage = false
                  bikePage = true
                  personalEbikePage = false
                  plcholder = plcholderForm.bike
                "
                >共享单车</el-menu-item
              >

              <el-menu-item
                index="1-3"
                @click="
                  get1stPagePersonalEBike()
                  EbikePage = false
                  bikePage = false
                  personalEbikePage = true
                  plcholder = plcholderForm.pebike
                "
                >个人电动车</el-menu-item
              >
            </el-menu-item-group>
          </el-submenu>

          <el-menu-item index="2">
            <i class="el-icon-s-data"></i>
            <span slot="title" @click="toStatistic"> 车辆统计 </span>
          </el-menu-item>

          <el-menu-item index="3">
            <i class="el-icon-location"></i>
            <span slot="title" @click="toCgpItemsInfo">充电桩信息</span>
          </el-menu-item>

          <!-- <el-menu-item index="4">
            <i class="el-icon-location"></i>
            <span slot="title">停车点信息</span>
          </el-menu-item> -->

          <!-- <el-menu-item index="5">
            <i class="el-icon-monitor"></i>
            <span slot="title">车辆数量管理</span>
          </el-menu-item> -->
        </el-menu>
      </el-aside>

      <el-container>
        <div style="margin-top: 10px"></div>
        <el-header style="text-align: right; font-size: 12px">
          <div style="width: 500px"></div>

          <div
            style="position: relative; float: left; top: 10px"
            v-show="personalEbikePage"
          >
            <div>
              <el-button
                type="primary"
                @click="dialogVisible = true"
                style="position: relative; top: -8px"
                ><i class="el-icon-plus"></i
              ></el-button>
            </div>
          </div>
          <div style="width: 200px; position: relative; float: right">
            <el-input
              v-model="input"
              :placeholder="plcholder"
              @keyup.enter.native="toFilterData"
            ></el-input>
          </div>
        </el-header>
        <el-dialog
          title="请输入车辆信息"
          :visible.sync="dialogVisible"
          width="30%"
          :before-close="handleClose1"
        >
          <el-form
            :model="form"
            status-icon
            :rules="rules1"
            ref="form"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="车辆编号" prop="no">
              <el-input v-model="form.no" autocomplete="off"></el-input>
            </el-form-item>

            <el-form-item label="权限">
              <el-select v-model="value" placeholder="请选择">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="时间范围" prop="timeInterval">
              <el-input
                v-model="form.timeInterval"
                autocomplete="off"
              ></el-input>
            </el-form-item>

            <el-form-item label="车牌颜色" prop="color">
              <el-input v-model="form.color" autocomplete="off"></el-input>
            </el-form-item>

            <el-form-item label="所属校区" prop="campus">
              <el-input v-model="form.campus" autocomplete="off"></el-input>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="submitForm('form')"
                >提交</el-button
              >
              <el-button @click="resetForm('form')">重置</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
        <div style="height: 628px">
          <el-table
            v-show="!personalEbikePage"
            stripe
            max-height="550"
            :data="tableData"
            border
            @cell-dblclick="editCell"
            @cell-click="cellClick"
          >
            <el-table-column fixed prop="id" label="序号" width="100">
            </el-table-column>
            <el-table-column prop="no" label="编号" width="110">
            </el-table-column>
            <el-table-column prop="state" label="使用状态" width="150">
              <template slot-scope="scope">
                <div v-if="row === scope.row.id && col === scope.column.id">
                  <el-input
                    placeholder=""
                    v-model="scope.row.state"
                    @blur="updateData"
                  ></el-input>
                </div>
                <div v-else>
                  {{ scope.row.state }}
                </div>
              </template>
            </el-table-column>

            <el-table-column prop="color" label="车牌颜色" width="150">
            </el-table-column>

            <el-table-column prop="battery" label="电量(%)" width="150">
            </el-table-column>

            <el-table-column
              prop="cumlative_usage_time"
              label="累计使用时长(h)"
              width="150"
            >
            </el-table-column>

            <el-table-column
              prop="monthly_usage_times"
              label="月使用次数"
              width="150"
            >
            </el-table-column>

            <el-table-column prop="position" label="位置(经,纬)" width="200">
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="success"
                  @click="openEdit(scope.$index, scope.row)"
                  >保存</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  @click="openDel(scope.$index, scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <!-- 个人电动车 -->
          <el-table
            v-show="personalEbikePage"
            stripe
            max-height="550"
            :data="tableData2"
            border
            @cell-dblclick="editCell2"
            @cell-click="cellClick2"
          >
            <el-table-column fixed prop="pebId" label="序号" width="100">
            </el-table-column>
            <el-table-column fixed prop="no" label="编号" width="150">
            </el-table-column>
            <el-table-column prop="ownership" label="权限" width="160">
            </el-table-column>
            <el-table-column prop="timeInterval" label="有效时间" width="300">
            </el-table-column>

            <el-table-column prop="campus" label="校区" width="300">
            </el-table-column>

            <el-table-column prop="color" label="车牌颜色" width="150">
            </el-table-column>

            <el-table-column label="操作" width="150">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="success"
                  @click="openEdit(scope.$index, scope.row)"
                  >保存</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  @click="openDel(scope.$index, scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <!-- 共享自行车分页 -->
          <div style="position: relative; left: 350px; top: 25px; width: 500px">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page.sync="currentPage3"
              :page-size="10"
              layout="prev, pager, next, jumper"
              :total="this.total"
              v-show="EbikePage"
            >
            </el-pagination>
          </div>
          <!-- 自行车分页 -->
          <div style="position: relative; left: 350px; top: 25px; width: 500px">
            <el-pagination
              @size-change="handleSizeChange2"
              @current-change="handleCurrentChange2"
              :current-page.sync="currentPage4"
              :page-size="10"
              layout="prev, pager, next, jumper"
              :total="this.total2"
              v-show="bikePage"
            >
            </el-pagination>
          </div>
          <!-- 个人电动车分页 -->
          <div style="position: relative; left: 350px; top: 25px; width: 500px">
            <el-pagination
              @size-change="handleSizeChange3"
              @current-change="handleCurrentChange3"
              :current-page.sync="currentPage5"
              :page-size="10"
              layout="prev, pager, next, jumper"
              :total="this.total3"
              v-show="personalEbikePage"
            >
            </el-pagination>
          </div>
        </div>
      </el-container>
    </el-container>
  </div>
</template>

<script>
export default {
  data() {
    var validateNo = (rule, value, callback) => {
      const reg = /^HN.\d{6}$/

      if (value === '') {
        callback(new Error('请输入编号'))
      } else if (!reg.test(value)) {
        callback(new Error("请输入正确编号，格式:'HN.xxxxxx',如:'HN000001'"))
      } else {
        if (this.form.checkPass !== '') {
          this.$refs.form.validateField('checkPass')
        }
        callback()
      }
    }

    const validateColor = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入车牌颜色'))
      } else {
        // this.$refs.form.validateField()
        callback()
      }
    }

    const validateTimeInterval = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入时间范围'))
      } else {
        callback()
      }
    }

    const validateCampus = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入所属校区'))
      } else {
        callback()
      }
    }
    return {
      input: '',
      plcholder: '请输入共享电动车编号',
      plcholderForm: {
        ebike: '请输入共享电动车编号',
        bike: '请输入共享单车编号',
        pebike: '请输入个人电动车编号',
      },
      form: {
        no: '',
        user: '',
        region: '',
        timeInterval: '',
        color: '',
        campus: '',
      },
      dialogVisible: false,
      row: '',
      col: '',
      tmpRow: '',
      row2: '',
      col2: '',
      tmpRow2: '',
      tableData: [],
      tableData2: [],
      activeIndex2: '1',
      activeName: 'second',
      EbikePage: true,
      personalEbikePage: false,
      bikePage: false,
      options: [
        {
          value: '学生',
          label: '学生',
        },
        {
          value: '教职工',
          label: '教职工',
        },
      ],
      value: '',
      currentPage3: 1,
      currentPage4: 1,
      currentPage5: 1,
      //共享单车总数
      total: 0,
      //共享单车总数
      total2: 0,
      total3: 0,
      rules: '',
      rules1: {
        no: [{ validator: validateNo, trigger: 'blur' }],
        color: [{ validator: validateColor, trigger: 'blur' }],
        timeInterval: [{ validator: validateTimeInterval, trigger: 'blur' }],
        campus: [{ validator: validateCampus, trigger: 'blur' }],
      },
    }
  },

  watch: {
    value(newV, old) {
      // console.log(newV);

      if (newV == 'using') {
        if (this.EbikePage) {
          // this.getItems("get", "getUnavailableEbike?page=1", 1);
          this.currentPage3 = 1
        }
      } else if (newV == 'repairing') {
        if (this.EbikePage) {
          // this.getItems("get", "getLogoutEbike?page=1", 1);
          this.currentPage3 = 1
        }
      } else if (newV == 'cancel') {
        if (this.EbikePage) {
          this.get1stPageSharedEbike()
        }
      }
    },
  },

  methods: {
    toStatistic() {
      let { href } = this.$router.resolve({
        path: '/statistic',
      })

      window.open(href, '_blank')
    },

    toCgpItemsInfo() {
      let { href } = this.$router.resolve({
        path: '/cgpItems',
      })

      window.open(href, '_blank')
    },

    search() {},

    // //查询
    toFilterData() {
      // 当用户没有输入内容就按enter键时，就return，不做任何操作，不去搜索
      if (this.input === '') {
        return
      } else {
        if (this.EbikePage) {
          this.$axios({
            method: 'get',
            url: `/searchSharedEBike?no=${this.input}`,
          }).then((res) => {
            if (res.data) {
              this.tableData = []
              this.total = 0

              const info = res.data
              const item = {
                // id: index + 1 + (val - 1) * 10,
                id: info.sebId,
                no: info.no,
                state: info.state,
                color: info.color || '无',
                battery: info.battery || '无',
                position: `${info.lng}` + ',' + `${info.lat}`,
                cumlative_usage_time: info.cumlativeUsageTime || '无',
                monthly_usage_times: info.monthlyUsageTimes,
              }

              this.tableData.push(item)
            } else {
              this.searchError()
            }
          })
        } else if (this.bikePage) {
          this.$axios({
            method: 'get',
            url: `/searchSharedBike?no=${this.input}`,
          }).then((res) => {
            if (res.data) {
              this.tableData = []
              this.total2 = 0

              const info = res.data
              const item = {
                // id: index + 1 + (val - 1) * 10,
                id: info.sbId,
                no: info.no,
                state: info.state,
                color: info.color || '无',
                battery: info.battery || '无',
                position: `${info.lng}` + ',' + `${info.lat}`,
                cumlative_usage_time: info.cumlativeUsageTime || '无',
                monthly_usage_times: info.monthlyUsageTimes,
              }

              this.tableData.push(item)
            } else {
              this.searchError()
            }
          })
        } else if (this.personalEbikePage) {
          this.$axios({
            method: 'get',
            url: `/searchPersonalEBike?no=${this.input}`,
          }).then((res) => {
            console.log(res)
            if (res.data) {
              this.tableData2 = []
              this.total3 = 0

              const info = res.data
              const item = {
                pebId: info.pebId,

                no: info.no,
                ownership: info.ownership,
                timeInterval: info.timeInterval,
                campus: info.campus,
                color: info.color,
              }

              this.tableData2.push(item)
            } else {
              this.searchError()
            }
          })
        }
      }
    },

    searchError() {
      this.$message({
        type: 'error',
        message: `没有找到该车辆`,
      })
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // alert("submit!");
          this.$message({
            message: '添加成功',
            type: 'success',
          })

          this.onSubmit()
          this.dialogVisible = false
        } else {
          // console.log("error submit!!");
          this.$message.error('信息有误')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleClose1(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          done()
        })
        .catch((_) => {})
    },
    onSubmit() {
      const newItem = {
        no: this.form.no,
        ownership: this.form.user,
        timeInterval: this.form.timeInterval,
        campus: this.form.campus,
        color: this.form.color,
      }

      this.tableData2.push(newItem)

      this.$axios({
        method: 'post',
        url: `/addPersonalEBike?no=${this.form.no}&ownership=${this.form.user}&timeInteravl=${this.form.timeInterval}&campus=${this.form.campus}&color=${this.form.color}`,
        data: newItem,
      }).then((res) => {
        console.log(res)
        if (res.status === 200) {
          this.$message({
            type: 'success',
            message: `添加成功`,
          })
        }
      })
    },
    handleClick(tab, event) {
      console.log(tab, event)
    },
    handleSelect(key, keyPath) {
      console.log(key, keyPath)
    },

    getItems(method, url, val) {
      this.$axios({
        method: method,
        url: url,
      }).then((res) => {
        this.tableData = []
        // this.total=0

        // console.log(res.data);

        if (this.EbikePage) {
          // this.total = res.data.total;
          this.getEBikeNum()

          for (let index = 0; index < res.data.length; index++) {
            const info = res.data[index]

            const item = {
              // id: index + 1 + (val - 1) * 10,
              id: info.sebId,
              no: info.no,
              state: info.state,
              color: info.color || '无',
              battery: info.battery || '无',
              position: `${info.lng}` + ',' + `${info.lat}`,
              cumlative_usage_time: info.cumlativeUsageTime || '无',
              monthly_usage_times: info.monthlyUsageTimes,
            }

            this.tableData.push(item)
          }
        } else if (this.bikePage) {
          // this.total2 = res.data.total;
          this.getBikeNum()

          for (let index = 0; index < res.data.length; index++) {
            const info = res.data[index]

            const item = {
              // id: index + 1 + (val - 1) * 10,
              id: info.sbId,
              no: info.no,
              state: info.state,
              color: info.color || '无',
              battery: info.battery || '无',
              position: `${info.lng}` + ',' + `${info.lat}`,
              cumlative_usage_time: info.cumlativeUsageTime || '无',
              monthly_usage_times: info.monthlyUsageTimes,
            }

            this.tableData.push(item)
          }
        }
      })
    },

    getPersonalEbikeItems(val) {
      this.$axios({
        method: 'get',
        url: `/personalEBike/pageRecords?current=${val}`,
      }).then((res) => {
        this.tableData2 = []

        for (let index = 0; index < res.data.length; index++) {
          const info = res.data[index]

          const item = {
            // id: index + 1 + (val - 1) * 10,
            pebId: info.pebId,

            no: info.no,
            ownership: info.ownership,
            timeInterval: info.timeInterval,
            campus: info.campus,
            color: info.color,
          }

          this.tableData2.push(item)
        }
      })
    },

    //电动车
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      //共享电动车分页

      if (this.value == 'unavailable') {
        this.getItems('get', `getUnavailableEbike?page=${val}`, val)
      } else if (this.value == 'logout') {
        this.getItems('get', `getLogoutEbike?page=${val}`, val)
      } else {
        this.getItems('get', `/sharedEBike/pageRecords?current=${val}`, val)
      }
    },

    //单车
    handleSizeChange2(val) {
      console.log(`每页 ${val} 条`)
    },

    handleCurrentChange2(val) {
      // 共享单车分页
      this.getItems('get', `/sharedBike/pageRecords?current=${val}`, val)
    },

    handleSizeChange3(val) {
      console.log(`每页 ${val} 条`)
    },

    handleCurrentChange3(val) {
      this.getPersonalEbikeItems(val)
    },

    //更新车辆信息
    openEdit(index, row) {
      this.$confirm('是否确认更改该车辆信息？', {
        distinguishCancelAndClose: true,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
      })
        .then(() => {
          this.handleEdit(index, row)
          this.$message({
            type: 'success',
            message: '更新成功',
          })
        })
        .catch((action) => {})
    },

    openDel(index, row) {
      this.$confirm('是否确认删除该车辆信息？', {
        distinguishCancelAndClose: true,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
      })
        .then(() => {
          this.handleDelete(index, row)
          this.$message({
            type: 'success',
            message: '删除成功',
          })
        })
        .catch((action) => {})
    },

    handleOpen(key, keyPath) {
      console.log(key, keyPath)
    },
    handleClose(key, keyPath) {
      console.log(key, keyPath)
    },

    handleEdit(index, row) {
      console.log(row)
      const data = {
        no: row.no,
        state: row.state,
      }

      //更新共享电动车信息
      if (this.EbikePage) {
        this.$axios({
          method: 'post',
          url: `updateSharedEBike?sebId=${row.id}&state=${row.state}`,
          data: data,
        }).then((res) => {
          console.log(res)
        })
      }
      //更新共享单车信息
      else if (this.bikePage) {
        this.$axios({
          method: 'post',
          url: `updateSharedBike?sbId=${row.id}&state=${row.state}`,
          data: data,
        }).then((res) => {
          console.log(res)
        })
      }
    },

    handleDelete(index, row) {
      console.log(row)
      //删除共享电动车

      if (this.EbikePage) {
        this.$axios({
          method: 'post',
          url: `deleteSharedEBike?sebId=${row.id}`,
          data: row,
        }).then((res) => {
          for (let index = 0; index < this.tableData.length; index++) {
            if (this.tableData[index].id == row.id) {
              this.tableData.splice(index, 1)
            }
          }
        })
      }
      //删除共享单车
      else if (this.bikePage) {
        this.$axios({
          method: 'post',
          url: `deleteSharedBike?sbId=${row.id}`,
          data: row,
        }).then((res) => {
          // console.log(res);

          for (let index = 0; index < this.tableData.length; index++) {
            if (this.tableData[index].id == row.id) {
              this.tableData.splice(index, 1)
            }
          }
        })
      } else if (this.personalEbikePage) {
        console.log('personal')
        this.$axios({
          method: 'post',
          url: `deletePersonalEBike?pebId=${row.pebId}`,
          data: row,
        }).then((res) => {
          // console.log(res);
          for (let index = 0; index < this.tableData2.length; index++) {
            if (this.tableData2[index].pebId == row.pebId) {
              this.tableData2.splice(index, 1)
            }
          }
        })
      }
    },

    editCell: function (row, column) {
      this.row = row.id
      this.col = column.id
      this.tmpRow = row
      this.tmpRow.id = row.id
    },

    editCell2: function (row2, column2) {
      this.row2 = row2.id
      this.col2 = column2.id
      this.tmpRow2 = row2
      this.tmpRow2.id = row2.id
    },

    updateData() {
      console.log(this.tmpRow.id)
      console.log(this.tmpRow.no)
      console.log(this.tmpRow.state)
      console.log(this.tmpRow.color)
    },

    cellClick() {
      // this.row = -1;
    },

    cellClick2() {},

    getAllSharedEbike() {
      this.$axios({
        method: 'get',
        url: 'getAllSharedEbike',
      }).then((res) => {
        // console.log(res.data);

        for (let index = 0; index < res.data.length; index++) {
          // console.log(res.data[index].color);
          const info = res.data[index]

          const item = {
            id: index + 1,
            no: info.no,
            state: info.state,
            color: info.color,
            battery: info.battery,
            position: `${info.lng}` + ',' + `${info.lat}`,
            cumlative_usage_time: info.cumlative_usage_time,
            monthly_usage_times: info.monthly_usage_times,
          }

          this.tableData.push(item)
        }
      })
    },

    //getEbike
    get1stPageSharedEbike() {
      // this.getItems("get", `getSharedEbikeByPage?page=${this.currentPage3}`, 1);
      this.getItems(
        'get',
        `/sharedEBike/pageRecords?current=${this.currentPage3}`,
        1
      )
    },

    getSharedEbikeByPage(val) {
      //分页查询
      this.$axios({
        method: 'get',
        // url: `getSharedEbikeByPage?page=${val}`,
        url: `/sharedEBike/pageRecords?current=${val}`,
      }).then((res) => {
        // console.log(res.data.data);

        this.tableData = []

        for (let index = 0; index < res.data.data.length; index++) {
          const info = res.data.data[index]

          const item = {
            id: index + 1 + (val - 1) * 10,
            no: info.no,
            state: info.state,
            color: info.color,
            battery: info.battery,
            position: `${info.lng}` + ',' + `${info.lat}`,
            cumlative_usage_time: info.cumlative_usage_time,
            monthly_usage_times: info.monthly_usage_times,
          }

          this.tableData.push(item)
        }
      })
    },

    //getBike
    get1stPageSharedBike() {
      // this.getItems("get", `getSharedBikeByPage?page=${this.currentPage4}`, 1);
      this.getItems(
        'get',
        `/sharedBike/pageRecords?current=${this.currentPage4}`,
        1
      )
    },

    get1stPagePersonalEBike() {
      this.getPersonalEBikeNum()
      this.getPersonalEbikeItems(this.currentPage5)
    },

    getEBikeNum() {
      this.$axios({
        method: 'get',
        url: '/getSharedEBikeNum',
      }).then((res) => {
        this.total = res.data
      })
    },

    getBikeNum() {
      this.$axios({
        method: 'get',
        url: '/getSharedBikeNum',
      }).then((res) => {
        this.total2 = res.data
      })
    },

    getPersonalEBikeNum() {
      this.$axios({
        method: 'get',
        url: '/getPersonalEBikeNum',
      }).then((res) => {
        this.total3 = res.data
      })
    },
  },

  mounted() {
    //     this.$axios({
    //   method:'get',
    //   url:'randInsert'
    // }).then(res=>{
    //   console.log(res);
    // })

    // this.$axios({
    //   method:'get',
    //   url:'randInsertB'
    // }).then(res=>{
    //   console.log(res);
    // })

    // this.$axios({
    //   method:'get',
    //   url:'insertC'
    // }).then(res=>{

    // })

    this.get1stPageSharedEbike()
  },
}
</script>

<style>
.el-header {
  background-color: #687581;
  color: #333;
  text-align: center;
  line-height: 60px;
}

.el-aside {
  background-color: #687581;
  color: #333;
  text-align: center;
  line-height: 200px;
  margin-right: 12px;
}

.el-main {
  /* height: 650px; */
}
</style>
